package com.huluobo.jetpackkotlindemo.lifecycle

import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.huluobo.jetpackkotlindemo.livedata_viewmodel.AdViewModel

/**
 * Created by lc on 2022/12/1.
 */
class AdManger(adViewModel: AdViewModel) : LifecycleObserver {
    companion object {
        const val TAG = "AdManger"
    }

    //定时器
    private var countDownTimer: CountDownTimer? =
        object : CountDownTimer(adViewModel.millisInFuture, 1000) {
            override fun onTick(millis: Long) {
                Log.i(TAG, "广告剩余${(millis / 1000).toInt()}秒")
                adViewModel.setAdTimingResult(millis/1000)//给ViewModel中的LiveData进行赋值
            }

            override fun onFinish() {
                Log.i(TAG, "广告结束,准备进入主页面")
            }
        }

    //计时开始
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun start() {
        Log.i(TAG, "开始计时")
        countDownTimer?.start()
    }

    //计时结束
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun cancel() {
        Log.i(TAG, "计时结束")
        countDownTimer?.cancel()
    }
}